/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package ex;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: jse2204 - Ticket
 * <p>Powered by webrx On 2022-09-30 11:12:36
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ticket implements Runnable {
    private int num = 50;
    private Set<Integer> set = new HashSet<>();
    public Ticket() {

    }

    public Ticket(int num) {
        Random rand = new Random();
        this.num = num;
        while(set.size()!=num){
            set.add(rand.nextInt(100,500));
        }
        System.out.println(set.size());
        System.out.println(set);
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        String t = Thread.currentThread().getName();
        System.out.println(t + "启动");
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            synchronized (this) {
                Random rand = new Random();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (this.set.size() == 0) break;
                   int ttt = 0;
                while(true) {
                    ttt = rand.nextInt(100, 500);
                    if(set.contains(ttt)) {
                        set.remove(ttt);
                        break;
                    }
                }
                System.out.printf("%s:售出(%d号)一张票，还有%d张票%n", t, ttt, set.size());
            }
        }
        System.out.println(t + "结束");
    }
}
